﻿package net.wangit.dev.wizard.element;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.wangit.LabelUtil;
import net.wangit.context.ActionContext;
import net.wangit.dev.wizard.WizardUtil;
import net.wangit.jdbc.ColumnRow;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.Table;


public class ASaveActionButton {

	public ASaveActionButton() {
	}

	public static final void create(DB db, ActionContext ac, String unitId,
			String tableName, String forward, List<String> elements,
			String sonUnitId, String sonTableName,
			Map<String, String> son2FatherFields) throws Exception {
		String elementId = WizardUtil.getElementId("save", elements);
		Table table = new Table("dev", "ELEMENT");
		ColumnRow cRow = table.addInsertRow();
		cRow.set("eid", elementId);
		cRow.set("uid", unitId);
		cRow.set("c", 41);
		cRow.set("l", "/common/images/tool/save.png");
		cRow.set("n", LabelUtil.get(ac, "dev", "toolbar.save"));
		cRow.set("b", 0);
		cRow.set("o", 9);
		cRow.set("a", "1");
		String command = (new StringBuilder(String.valueOf(tableName))).append(
				",").append(unitId).append(";").toString();
		String validateUnits = unitId;
		if (sonUnitId != null) {
			String sonTableFieldsCommand = getFieldsCommand(son2FatherFields,
					unitId);
			command = (new StringBuilder(String.valueOf(command))).append(
					sonTableName).append(",").append(sonUnitId).append(",")
					.append(sonTableFieldsCommand).append(";").toString();
			validateUnits = (new StringBuilder(String.valueOf(validateUnits)))
					.append(",").append(sonUnitId).toString();
		}
		cRow.set("ac", command);
		cRow.set("av", validateUnits);
		cRow.set("asf", forward);
		cRow.set("aff", forward);
		cRow.set("asm", LabelUtil.get(ac, "dev", "action.save.1"));
		cRow.set("afm", LabelUtil.get(ac, "dev", "action.save.0"));
		cRow.set("ms", 9);
		cRow.set("au", 1);
		cRow.set("aum", 9);
		cRow.set("s", 1);
		db.save(table);
	}

	private static String getFieldsCommand(
			Map<String, String> son2FatherFields, String fatherUnitId) {
		StringBuffer result = new StringBuffer();
		Set<String> keySet = son2FatherFields.keySet();
		for (Iterator<String> keys = keySet.iterator(); keys.hasNext();) {
			String sonColumnName = keys.next();
			String fatherColumnName = son2FatherFields.get(sonColumnName);
			result.append(sonColumnName).append("=").append(fatherUnitId)
					.append(".").append(fatherColumnName);
			if (keys.hasNext())
				result.append("/");
		}

		return result.toString();
	}
}
